package com.chatplus.application.aiprocessor.platform.chat.chatglm;

import cn.bugstack.openai.executor.model.chatglm.config.ChatGLMConfig;
import cn.bugstack.openai.executor.parameter.CompletionRequest;
import cn.bugstack.openai.session.Configuration;
import cn.bugstack.openai.session.OpenAiSession;
import cn.bugstack.openai.session.OpenAiSessionFactory;
import cn.bugstack.openai.session.defaults.DefaultOpenAiSessionFactory;
import com.chatplus.application.aiprocessor.listener.CommonEventSourceListener;
import com.chatplus.application.aiprocessor.platform.chat.ChatProcessorService;
import com.chatplus.application.aiprocessor.provider.ChatAiProcessorServiceProvider;
import com.chatplus.application.common.constant.GroupCacheNames;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.common.util.CacheGroupUtils;
import com.chatplus.application.domain.dto.ChatConfigDto;
import com.chatplus.application.domain.dto.ws.ChatRecordMessage;
import com.chatplus.application.enumeration.AiPlatformEnum;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * ChatGLM 机器人处理器
 *
 * @author chj
 * @date 2023/12/27
 **/
@Service(value = ChatAiProcessorServiceProvider.SERVICE_NAME_PRE + "ChatGLM")
public class ChatGLMProcessor extends ChatProcessorService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ChatGLMProcessor.class);

    @Override
    public void processStream() throws Exception {
        CompletionRequest request = getCompletionRequest();
        // 1. 创建参数
        ChatConfigDto.ChatGmlSetting chatGmlSetting = CacheGroupUtils.get(GroupCacheNames.SYS_AI_SETTING, getChannel());
        if (chatGmlSetting != null) {
            request.setMaxTokens(chatGmlSetting.getMaxTokens());
            request.setTemperature(chatGmlSetting.getTemperature());
        }
        OpenAiSession openAiSession = getSessionFactory();
        if (openAiSession != null) {
            openAiSession.completions(request, new CommonEventSourceListener(chatRequest));
        }
    }

    @Override
    public String processSync() {
        return null;
    }

    @Override
    public AiPlatformEnum getChannel() {
        return AiPlatformEnum.CHAT_GLM;
    }

    @Override
    public void initSessionFactory() {
        instance();
        // 需要用竖线（|）将 APPID, APIKey 和 APISecret 按照顺序串接起来填入
        OPEN_API_KEY_CACHE.forEach(item -> {
            ChatGLMConfig chatGLMConfig = new ChatGLMConfig();
            chatGLMConfig.setApiHost(item.getUrl());
            chatGLMConfig.setApiSecretKey(item.getApiKey());
            // 2. 配置文件
            Configuration configuration = new Configuration();
            configuration.setLevel(HttpLoggingInterceptor.Level.HEADERS);
            configuration.setChatGLMConfig(chatGLMConfig);
            configuration.setProxyUrl(item.getProxyUrl());
            // 3. 会话工厂
            OpenAiSessionFactory factory = new DefaultOpenAiSessionFactory(configuration);
            OPEN_AI_SESSION_CACHE.put(getChannel(), factory.openSession());
        });
    }
}